package com.lyw.forum.common.advice;

import com.lyw.forum.common.enums.ResultCode;
import com.lyw.forum.common.exception.ApplicationException;
import com.lyw.forum.pojo.response.AppResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@ResponseBody
@ControllerAdvice
public class ExceptionAdvice {

    @ExceptionHandler(ApplicationException.class)
    public AppResult applicationExceptionHandler(ApplicationException e) {
        //打印日志
        log.error("ApplicationException: {}", e.getMessage());

        if (e.getErrorResult() != null) {
            return e.getErrorResult();
        }

        //非空校验
        if (!StringUtils.hasLength(e.getMessage())) {
            return AppResult.fail(ResultCode.ERROR_SERVICES);
        }

        //返回具体的错误信息
        return AppResult.fail(e.getMessage());

    }

    @ExceptionHandler(Exception.class)
    public AppResult exceptionHandler(Exception e) {
        //打印日志
        log.error("Exception: {}", e.getMessage());

        //非空校验
        if (!StringUtils.hasLength(e.getMessage())) {
            return AppResult.fail(ResultCode.ERROR_SERVICES);
        }

        //返回具体的错误信息
        return AppResult.fail(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AppResult exceptionHandler(MethodArgumentNotValidException exception) {
        String msg = exception.getBindingResult().getFieldError().getDefaultMessage();
        log.error("发生异常, e: {}", exception.getMessage());

        return AppResult.fail(msg);
    }
}
